#
#  This library provides a simple template (stpl) system for ascii txt files.
#  It is made to use with libinclude.sh.
#  
#  Synopsis:
#     stpl_fill TPL_FILE [VPREFIX]
#     stpl_check TPL_FILE [VPREFIX]
#     stpl_show TPL_FILE [VPREFIX]
#	  stpl_data TPL_FILE [VPREFIX]
#
# depends on column

# default prefix for input variables
VPREFIX='TPL'

# opening and closing string for keys in template
# note: mask special characters!
KEYOPEN='\\['
KEYCLOSE='\\]'

# automatical check (1) if all variables used in
# TPL_FILE are set and not empty or not (0)
ACHECK=0

# should stpl_check exit (1) or cast only a warning (0) 
# if a variable (used in TPL_FILE) is empty or not set
HCHECK=0

# variable which will be ignored if empty or not set
# while variables used in TPL_FILE are checked
SVAR='SW0 SW1 SW2 SW3 SW4 SW5 SW6 SW7 SW8 SW9'

___prepro(){
	local pf
	if [ ! -f $1 ]; then
		echo "(stpl.sh) ERROR: File $1 did not exist!"
		exit 1
	fi
	if [ "$2" = '' ]; then
		pf="${VPREFIX}_"
	else
		pf="$2_"
	fi
	echo $pf	
}

___keys(){
	local k0 k1 out
	k0="$KEYOPEN"
	k1="$KEYCLOSE"
	out=$(cat $1 | sed -n "s/.*$k0\\(.*\\)$k1.*/\\1/p")
	echo $out | awk '{ while(++i<=NF) printf (!a[\$i]++) ? \$i FS : ""; i=split("",a); print "" }'
}

___svar(){
	local tmp
	tmp=$(echo $SVAR | grep $1 | wc -w)
	if [ $tmp -eq 0 ]; then
		echo ''
	else
		echo 'true'
	fi
}

fill (){
	local pf keys key val line
	pf=$( ___prepro $1 $2 )
	keys=$( ___keys $1 )
	[ $ACHECK -eq 1 ] && check $1 $2
	while read line; do
		for key in $keys; do
			eval val="\\$${pf}${key}"
			line=$(echo $line | sed "s/${KEYOPEN}${key}${KEYCLOSE}/${val}/")
		done
		echo "$line"
	done < $1
}

check (){
	local pf keys key val error
	error=0
	pf=$( ___prepro $1 $2 )
	keys=$( ___keys $1 )
	for key in $keys; do
		eval val="\\$${pf}${key}"
		if [ -z "$val"	] && [ ! $( ___svar $key ) ]; then
			if [ $HCHECK -eq 1 ]; then
				echo "(stpl.sh) ERROR: Variable ($pf)$key is empty or not set!"
				exit 1
			else
				echo "(stpl.sh) Warning: Variable ($pf)$key is empty or not set!"
				error=$(($error+1))
			fi
		fi
	done
	[ $error -eq 0 ] && echo 0
}

show (){
	local pf keys key val out
	pf=$( ___prepro $1 $2 )
	keys=$( ___keys $1 )
	out="key%value&========%========&"
	for key in $keys; do
		eval val="\\$${pf}${key}"
		out="${out}${key}%${val}&"
	done
	echo $out | tr "&" "\\n" | column -t -s '%'
}

data (){
	local pf keys key val
	pf=$( ___prepro $1 $2 )
	keys=$( ___keys $1 )
	for key in $keys; do
		eval val="\\$${pf}${key}"
		echo "${key}=\'${val}\'"
	done
}
